<?php
/*******************************************************************************

    FinalsClub.org is a platform for students and faculty to collaborate
    and share their knowledge with the world.

    Copyright (C) 2009  Andrew Magliozzi

    This file is a part of FinalsClub.org.

    FinalsClub.org is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    To contact FinalsClub.org, send an email to info@finalsclub.org, or
    send mail to Finals Club, c/o Veritas Tutors, 1132 Massachusetts Avenue,
    Cambridge, MA 02138.

*******************************************************************************/

/**
 * user_profiles actions.
 *
 * @package    FinalsClub
 * @subpackage user_profiles
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
 */
class user_profilesActions extends sfActions {
	
	/**
	 * Display an individual user's profile
	 * @param $request
	 * @return unknown_type
	 */
	public function executeShow($request) {
		
		$id = $request->getParameter('id', $this->getUser()->getId());
		$user_profile = UserProfilePeer::retrieveByUserId($id);
		$user = UserPeer::retrieveById($id);
		$this->user_profile = $user_profile;
		$this->user = $user;
		
		$this->subjects = SubjectPeer::doSelect(new Criteria());
	}
	
	public function executeLibrary($request) {
			//retrieve user's profile for a given id
			$user_id = $request->getParameter('id');
			return $this->renderComponent('library','profileList', array('user_id'=>$user_id));
	}
	
	public function executeRecentactivity($request) {
	
		//user id of person viewing this profile
		$viewer = $this->getUser()->getId();

		$feeds = ActivityFeedPeer::retrieveRecentActivityByUserId($request->getParameter('id'),$viewer);	

		//group feeds by date
		$today = strtotime('today');
		$yesterday = strtotime('yesterday');
		$todays_feeds = array();
		$yesterdays_feeds = array();
		$older_feeds = array();
		foreach($feeds as $feed) {
			$feed_date = $feed->getUpdatedAt();
			
			if(strtotime($feed_date) >= $today)
				$todays_feeds[] = $feed;
			else if(strtotime($feed_date) >= $yesterday)
				$yesterdays_feeds[] = $feed;
			else
				$older_feeds[strftime('%A, %b %d', strtotime($feed->getUpdatedAt()))][] = $feed;
		}
		
		$feeds = array('TODAY'=>$todays_feeds, 'YESTERDAY'=>$yesterdays_feeds);
		$feeds = array_merge($feeds, $older_feeds);
		
		$viewable_feeds = $feeds;
		
		return $this->renderPartial('recentActivity', array('feeds'=>$viewable_feeds));
	}
	
	public function executeNotes($request) {
		
			$user_id = $request->getParameter('id');
			return $this->renderComponent('notes','profileDetail', array('user_id'=>$user_id));
	}
	
	public function executeCourses($request) {
		
			$user_id = $request->getParameter('id');
		
			return $this->renderComponent('courses','profileList', array('user_id'=>$user_id));
	}
	
	public function executeAnnotations($request) {
		
			$user_id = $request->getParameter('id');
		
			return $this->renderComponent('annotations', 'profileDetail', array('user_id'=>$user_id));
	}	
	
	/**
	 * Present a form for editing a user's profile
	 * @param $request
	 * @return unknown_type
	 */
	public function executeEdit($request) {		
		$user_profile = UserProfilePeer::retrieveByUserId($this->getUser()->getId());
		$this->profile_form = new UserProfileForm($user_profile);
		
		$user = UserPeer::retrieveById($this->getUser()->getId());
		$this->user = $user;
		$this->user_form = new UserForm($user);
		
		$this->prof = ProfPeer::retrieveByUserId($user->getid());
		
		$this->form = new UserProfileForm($user_profile);
		$this->form->embedForm('user', new UserForm($user));
	}
	
	
	/**
	 * Make an existing user's account a facebook connect account.
	 * @param $request
	 */
	public function executeConnect($request) {
		$user = UserPeer::retrieveById($this->getUser()->getId());
		$error = null;
		
		$fb_uid = FacebookUtility::facebook_client()->get_loggedin_user();
		if (!$fb_uid) {
			throw new Exception('No authenticated facebook user');
		}
		$existing_fb_user = UserPeer::retrieveByFacebookId($fb_uid);
		if ($existing_fb_user != null) {
			$error = 'Sorry, a Finals Club member is already associated with that Facebook account';
		} else {
			$this->getUser()->setAttribute('facebook_id', $fb_uid);
			$user->setFacebookId($fb_uid);
			$user->save();
		}
		
		if (isset($error)) {
			$this->getUser()->setFlash('error', $error);
		} else {
			$this->getUser()->setFlash('success', 'Your account was successfully connected with Facebook');
		}
		$this->setTemplate('edit');
		self::executeEdit($request);
	}
	

	/**
	 * Update a user's profile
	 * @param $request
	 * @return unknown_type
	 */
	public function executeUpdate($request) {
		//print_r($request->getParameter('user_profile'));
		$user_profile = $request->getParameter('user_profile');
		$user_profile['user_id'] = $this->getUser()->getId();	// make sure and set the user id for the profile

		$profile = UserProfilePeer::retrieveByUserId($this->getUser()->getId());
		$this->form = new UserProfileForm($profile);
		
		$profile = $this->form->updateObject($user_profile);
		$profile->save();	// update the user's profile
		$this->form = new UserProfileForm($profile);	// re-create the form from the newly updated/created profile
		
		// retrieve and update the current user
		$user = UserPeer::retrieveById($this->getUser()->getId());
		$this->user = $user;
		$user_form = new UserForm($user);

		// update the user's account information
		$user_account = null;
		if(isset($user_profile['user'])) {
			$user_account = $user_profile['user'];
			$user = $user_form->updateObject($user_account);
		}		

		// process the file if the user has uploaded an avatar
		$files = $request->getFiles('user_profile');	
		if($files && count($files) > 0) {
			$fileValues = array();
			// remove and clean off the avatar namespace from the array
			foreach($files as $key => $value) {
				$fileValues[$key] = $value['user']['avatar'];
			}

			if($fileValues['size'] > 0) {
				$file = $user_form->saveAvatar($fileValues);	// process the file to the filesystem	
			}
		}
		
				//change password
		if(array_key_exists('old_pw',$user_profile)){		 
			if($user_profile['old_pw'] != ""){
				if(strcmp(md5($user_profile['old_pw']),$user_form['md5_password']->getValue()) == 0 ) { //check validity of old password
				
					if($user_profile['user']['password'] == $user_profile['user']['confirm_password'] ) { //check that two new password fields match
					
						$user->setMd5Password(md5($user_profile['user']['password']));
						$message = "Password Change Successful!";
					}
					else{
						$message = "Change Password Operation Failed: Confirmed password does not match.";
					}	
				}
				else{
					$message = "Change Password Operation Failed: Old Password Incorrect.";
				}				
			}
			else{
			
				$message=null;
				
			}
		}


		$user->save();	// save and update the user's account
		$this->form->embedForm('user', new UserForm($user));	// re-embed the user form within the user profile form

		$this->getUser()->setFlash('success', 'Your profile has been successfully updated');
		
		if(isset($message)){
			$this->getUser()->setFlash('success', $message);
		}
		// re-update the user's session
		$this->getUser()->login($this->getUser()->getId());
		$this->redirect('user_profiles/show?id='.$this->getUser()->getId());
	}
}
